package com.sita.bike.ui.activity.roadtrust;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sita.bike.R;
import com.sita.bike.support.GlobalContext;

import java.util.ArrayList;
import java.util.List;

public class PoiAroundSearchActivity extends AppCompatActivity{
    private PoiSearch.Query query;// Poi查询条件类
    private String deepType = "";// poi搜索类型
    private int currentPage = 0;// 当前页面，从0开始计数
    private LatLonPoint lp = new LatLonPoint(39.908127, 116.375257);// 默认西单广场
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private List<PoiItem> poiItems;// poi数据
    private List<String> poiitemdata= new ArrayList<>();
    private ListView poilst;
    private Button my_location_back, bt_search_cancel;
    private EditText tv_search;
    ;

    public PoiAroundSearchActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poi_around_search);
        poilst = (ListView) findViewById(R.id.poilst);
        my_location_back = (Button) findViewById(R.id.my_location_back);
        tv_search = (EditText) findViewById(R.id.tv_search);
        bt_search_cancel = (Button) findViewById(R.id.bt_search_cancel);
        Bundle bundle = getIntent().getExtras();
        double latitude = bundle.getDouble("Latitude");
        double longitude = bundle.getDouble("Longitude");
        lp.setLatitude(latitude);
        lp.setLongitude(longitude);
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        final String city = location.getCity();
        final ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.poi_search_listview_item, poiitemdata);
        poilst.setAdapter(adapter);
        poilst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView poi_search_listview_item = (TextView) view.findViewById(R.id.poi_search_listview_item);
                String poi_search_item_tv = poi_search_listview_item.getText().toString();
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("myLocation", poi_search_item_tv);
                intent.putExtras(bundle);
                setResult(0, intent);
                finish();
            }
        });
        doSearchQuery(city, adapter);
        my_location_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("myLocation", "所在位置");
                intent.putExtras(bundle);
                setResult(0, intent);
                finish();
            }
        });
        bt_search_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_search.setText("");
                poiitemdata.clear();
                doSearchQuery(city, adapter);
            }
        });
        tv_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String location_key = tv_search.getText().toString();
                query = new PoiSearch.Query(location_key, "", city);
                query.setPageSize(10);// 设置每页最多返回多少条poiitem
                query.setPageNum(currentPage);//设置查询页码
                poiSearch = new PoiSearch(getApplicationContext(), query);//初始化poiSearch对象
                poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                    @Override
                    public void onPoiSearched(PoiResult result, int rCode) {
                        if (rCode == 0) {
                            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                                if (result.getQuery().equals(query)) {// 是否是同一条
                                    poiResult = result;
                                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                                    poiitemdata.clear();
                                    poiitemdata.add("不显示位置");
                                    for (int i = 0; i < poiItems.size(); i++) {
                                        PoiItem poiItem = poiItems.get(i);
                                        poiitemdata.add(poiItem.getTitle());
                                    }
                                    adapter.notifyDataSetChanged();
                                    List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                                }
                            }
                        }
                    }

                    @Override
                    public void onPoiItemSearched(PoiItem poiItem, int i) {

                    }

                });//设置回调数据的监听器
                poiSearch.searchPOIAsyn();//开始搜索


            }
        });

    }


//    class PoiSearch implements View.OnClickListener,

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String city, final ArrayAdapter arrayadapter) {
        currentPage = 0;
        query = new PoiSearch.Query("", "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        if (lp != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                @Override
                public void onPoiSearched(PoiResult result, int rCode) {
                    if (rCode == 0) {
                        if (result != null && result.getQuery() != null) {// 搜索poi的结果
                            if (result.getQuery().equals(query)) {// 是否是同一条
                                poiResult = result;
                                poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                                poiitemdata.add("不显示位置");
                                for (int i = 0; i < poiItems.size(); i++) {
                                    PoiItem poiItem = poiItems.get(i);
                                    poiitemdata.add(poiItem.getTitle());
                                }
                                arrayadapter.notifyDataSetChanged();
                            }
                        }
                    }
                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {

                }
            });
            poiSearch.setBound(new PoiSearch.SearchBound(lp, 2000, true));//
            // 设置搜索区域为以lp点为圆心，其周围2000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("myLocation", "所在位置");
            intent.putExtras(bundle);
            setResult(0, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
